`
https://leetcode.cn/problems/count-the-number-of-fair-pairs/
`

/**
 * @param {number[]} nums
 * @param {number} lower
 * @param {number} upper
 * @return {number}
 */
var countFairPairs = function (nums, lower, upper) {
  nums.sort((a, b) => a - b)
  return count(nums, upper) - count(nums, lower - 1)
};

// 传入的 nums 应当是有序的
// 计算 i < j 且 nums[i] + nums[j] <= upper 的 j 的个数
function count(nums, upper) {
  let res = 0
  let j = nums.length - 1

  for (let i = 0; i < nums.length; i++) {
    while (j > i && nums[j] > upper - nums[i]) {
      j--
    }
    if (j === i) break
    res += j - i
  }
  return res
}